'use client'

import { useState, useEffect } from 'react'
import { 
  Layout, Menu, Button, Space, Badge, Avatar, Dropdown, 
  Typography, Row, Col, message 
} from 'antd'
import {
  HomeOutlined, ShopOutlined, QrcodeOutlined, 
  ShoppingCartOutlined, UserOutlined, LoginOutlined,
  LogoutOutlined, SettingOutlined
} from '@ant-design/icons'
import Link from 'next/link'
import { useRouter, usePathname } from 'next/navigation'
import { STORAGE_KEYS } from '@/utils/constants'

const { Header: AntHeader } = Layout
const { Title } = Typography

interface User {
  id: number
  username: string
  userType: string
  avatarUrl?: string
}

export default function Header() {
  const [user, setUser] = useState<User | null>(null)
  const [cartCount, setCartCount] = useState(0)
  const router = useRouter()
  const pathname = usePathname()

  // 检查是否为管理后台路径
  const isAdminPath = pathname.startsWith('/admin')

  useEffect(() => {
    // 检查登录状态
    const token = localStorage.getItem(STORAGE_KEYS.TOKEN)
    const userStr = localStorage.getItem(STORAGE_KEYS.USER)
    
    if (token && userStr) {
      try {
        const userData = JSON.parse(userStr)
        setUser(userData)
        // TODO: 获取购物车数量
        // loadCartCount()
      } catch (error) {
        console.error('Parse user data error:', error)
        logout()
      }
    }
  }, [])

  const logout = () => {
    localStorage.removeItem(STORAGE_KEYS.TOKEN)
    localStorage.removeItem(STORAGE_KEYS.USER)
    setUser(null)
    setCartCount(0)
    message.success('已退出登录')
    router.push('/')
  }

  const menuItems = [
    {
      key: '/',
      icon: <HomeOutlined />,
      label: <Link href="/">首页</Link>
    },
    {
      key: '/products',
      icon: <ShopOutlined />,
      label: <Link href="/products">产品中心</Link>
    },
    {
      key: '/trace',
      icon: <QrcodeOutlined />,
      label: <Link href="/trace">产品溯源</Link>
    }
  ]

  const userMenuItems = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人中心'
    },
    {
      key: 'orders',
      icon: <ShopOutlined />,
      label: <Link href="/orders">我的订单</Link>
    },
    ...(user?.userType === 'ADMIN' ? [
      {
        key: 'admin',
        icon: <SettingOutlined />,
        label: <a href="/admin" target="_blank" rel="noopener noreferrer">管理后台</a>
      }
    ] : []),
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '账户设置'
    },
    {
      key: 'divider',
      type: 'divider' as const
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: logout
    }
  ]

  // 隐藏头部的页面
  const hideHeaderPages = ['/login', '/register']
  if (hideHeaderPages.includes(pathname)) {
    return null
  }

  // 如果是管理后台路径，则不显示C端导航菜单
  if (isAdminPath) {
    return (
      <AntHeader style={{ 
        background: '#001529', 
        padding: '0 24px',
        position: 'sticky',
        top: 0,
        zIndex: 1000,
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <Row justify="space-between" align="middle" style={{ height: '100%' }}>
          <Col>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Link href="/admin" style={{ textDecoration: 'none' }}>
                <Title level={3} style={{ 
                  color: 'white', 
                  margin: 0, 
                  fontSize: '20px'
                }}>
                  管理后台
                </Title>
              </Link>
            </div>
          </Col>
          
          <Col>
            <Space size="large">
              {user ? (
                <>
                  <Dropdown 
                    menu={{ items: userMenuItems }}
                    placement="bottomRight"
                  >
                    <Space style={{ cursor: 'pointer', color: 'white' }}>
                      <Avatar 
                        src={user.avatarUrl} 
                        icon={<UserOutlined />}
                        size="small"
                      />
                      <span>{user.username}</span>
                    </Space>
                  </Dropdown>
                </>
              ) : (
                <Space>
                  <Link href="/login">
                    <Button type="text" icon={<LoginOutlined />} style={{ color: 'white' }}>
                      登录
                    </Button>
                  </Link>
                </Space>
              )}
            </Space>
          </Col>
        </Row>
      </AntHeader>
    )
  }

  return (
    <AntHeader style={{ 
      background: '#001529', 
      padding: '0 24px',
      position: 'sticky',
      top: 0,
      zIndex: 1000,
      boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
    }}>
      <Row justify="space-between" align="middle" style={{ height: '100%' }}>
        <Col>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Link href="/" style={{ textDecoration: 'none' }}>
              <Title level={3} style={{ 
                color: 'white', 
                margin: 0, 
                marginRight: '40px',
                fontSize: '20px'
              }}>
                🐟 海产品交易平台
              </Title>
            </Link>
            
            <Menu
              theme="dark"
              mode="horizontal"
              selectedKeys={[pathname]}
              items={menuItems}
              style={{ 
                background: 'transparent', 
                border: 'none',
                minWidth: '350px'  // 增加最小宽度以确保菜单项始终可见
              }}
            />
          </div>
        </Col>
        
        <Col>
          <Space size="large">
            {user ? (
              <>
                <Link href="/cart">
                  <Badge count={cartCount} showZero={false}>
                    <Button 
                      type="text" 
                      icon={<ShoppingCartOutlined />} 
                      style={{ color: 'white' }}
                    >
                      购物车
                    </Button>
                  </Badge>
                </Link>
                
                <Dropdown 
                  menu={{ items: userMenuItems }}
                  placement="bottomRight"
                >
                  <Space style={{ cursor: 'pointer', color: 'white' }}>
                    <Avatar 
                      src={user.avatarUrl} 
                      icon={<UserOutlined />}
                      size="small"
                    />
                    <span>{user.username}</span>
                  </Space>
                </Dropdown>
              </>
            ) : (
              <Space>
                <Link href="/login">
                  <Button type="text" icon={<LoginOutlined />} style={{ color: 'white' }}>
                    登录
                  </Button>
                </Link>
                <Link href="/register">
                  <Button type="primary">
                    注册
                  </Button>
                </Link>
              </Space>
            )}
          </Space>
        </Col>
      </Row>
    </AntHeader>
  )
}